﻿using System;

namespace Microsoft.Popfly.GameCreator.GameEngine.Events
{
    public class StateChangeEventChecker : IEventChecker
    {
        private Actor m_owner;
        private State m_oldState;
        private string m_stateName;

        public StateChangeEventChecker(BehaviorOwner owner, String state)
        {
            if (owner.GetType() != typeof(Actor))
            {
                throw new ArgumentException(
                    Utils.ErrorMessagePrefix +
                    "State change events only apply to Actors, but one is being created for a '" + 
                    owner.GetType().ToString() + 
                    "'."
                    );
            }

            m_owner = (Actor)owner;
            m_oldState = m_owner.CurrentState;
            m_stateName = state;
        }

        #region IEventChecker Members

        public bool FireThisFrame(double elapsedTimeInSeconds, out BehaviorOwner sender, out PGCEventArgs args)
        {
            if (m_oldState == null)
            {
                m_oldState = m_owner.CurrentState;
                sender = null;
                args = null;
                return false;
            }
            // Compat hack - changedthisframe is used to simulate the old behavior where
            // state change events wouldn't get processed until the frame after the state
            // actually changed
            else if (m_oldState == m_owner.CurrentState || m_owner.ChangedStateThisFrame)
            {
                sender = null;
                args = null;
                return false;
            }
            else
            {
                m_oldState = m_owner.CurrentState;

                if (m_owner.CurrentState.Name == m_stateName)
                {
                    sender = m_owner;
                    args = new StateChangeEventArgs(m_oldState, m_owner.CurrentState);
                    return true;
                }
                else
                {
                    sender = null;
                    args = null;
                    return false;
                }
            }
        }

        public bool IsOfEventType(string eventType)
        {
            return eventType == "StateChange";
        }

        #endregion
    }
}
